/*
  InsertInlineRectangleAtParagraphStart_ID2022_fix.jsx
  用法：
  1) 在文档中先选中一个 Rectangle（矩形对象，内含图片或纯色块都可）。
  2) 运行脚本，选择目标段落样式。
  3) 脚本将该矩形作为“内联锚定对象”插到所有匹配段落的段首。
*/

(function () {
    if (app.documents.length === 0) { alert("请先打开一个文档。"); return; }
    var doc = app.activeDocument;

    // 仅接受 Rectangle —— InDesign 用 constructor.name 判断类型
    if (app.selection.length !== 1 || app.selection[0].constructor.name !== "Rectangle") {
        // 备选：若你的环境支持，也可用 instanceof
        // if (app.selection.length !== 1 || !(app.selection[0] instanceof Rectangle)) { ... }
        alert("请先选中一个 Rectangle（矩形对象）。");
        return;
    }
    var srcRect = app.selection[0];

    // ===== 收集全部段落样式（包含组内样式） =====
    var allStyles = doc.allParagraphStyles; // 官方 DOM：含组内样式
    var styles = [];       // 实际可选样式
    var styleNames = [];   // 下拉显示名称（带组路径）

    function fullStyleName(s) {
        var n = s.name;
        var p = s.parent;
        // InDesign 同样用 constructor.name 判断是否为样式组
        while (p && p.constructor && p.constructor.name === "ParagraphStyleGroup") {
            n = p.name + " / " + n;
            p = p.parent;
        }
        return n;
    }

    var basic = doc.paragraphStyles[0]; // [Basic Paragraph]（本地化名称无影响）
    for (var i = 0; i < allStyles.length; i++) {
        var s = allStyles[i];
        if (s === basic) continue; // 过滤 [Basic Paragraph]
        if (s.name === "[No Paragraph Style]") continue;
        styles.push(s);
        styleNames.push(fullStyleName(s));
    }
    if (styles.length === 0) { alert("文档中没有可用的段落样式。"); return; }

    // ===== 对话框 =====
    var dlg = new Window("dialog", "段首插入矩形（内联锚定）");
    dlg.alignChildren = "fill";

    var g1 = dlg.add("group");
    g1.add("statictext", undefined, "目标段落样式：");
    var dd = g1.add("dropdownlist", undefined, styleNames);
    dd.selection = 0;

    var cbSkipExisting = dlg.add("checkbox", undefined, "跳过已以锚定对象开头的段落（推荐）");
    cbSkipExisting.value = true;

    var g2 = dlg.add("group");
    g2.alignment = "right";
    g2.add("button", undefined, "确定", { name: "ok" });
    g2.add("button", undefined, "取消", { name: "cancel" });

    if (dlg.show() !== 1) return;
    var targetStyle = styles[dd.selection.index];

    // ===== 一次性撤销封装 =====
    app.doScript(function () {

        // 复制一次，后续粘贴
        app.select(srcRect);
        app.clipboardPreferences.pasteRemembersLayers = true;
        app.copy();

        // GREP：查找目标段落样式的“段首”
        app.findGrepPreferences    = NothingEnum.NOTHING;
        app.changeGrepPreferences  = NothingEnum.NOTHING;
        try {
            app.findChangeGrepOptions.includeFootnotes = true;
            app.findChangeGrepOptions.includeHiddenLayers = true;
            app.findChangeGrepOptions.includeLockedLayersForFind = false;
            app.findChangeGrepOptions.includeLockedStoriesForFind = false;
            app.findChangeGrepOptions.includeMasterPages = false;

            app.findGrepPreferences.findWhat = "^";
            app.findGrepPreferences.appliedParagraphStyle = targetStyle;

            var hits = doc.findGrep();
            if (!hits || hits.length === 0) { alert("没有找到应用该段落样式的段落。"); return; }

            var done = 0, skipped = 0, failed = 0;

            for (var i = 0; i < hits.length; i++) {
                try {
                    var ip = hits[i].insertionPoints[0];

                    if (cbSkipExisting.value) {
                        var para = ip.paragraphs[0];
                        var hasAnchorAtStart = false;
                        if (para.characters.length > 0) {
                            var firstChar = para.characters[0];
                            if (firstChar.contents === SpecialCharacters.ANCHOR_MARKER) {
                                hasAnchorAtStart = true;
                            }
                        }
                        if (hasAnchorAtStart) { skipped++; continue; }
                    }

                    app.select(ip);
                    app.paste(); // 作为“内联锚定对象”插入

                    done++;
                } catch (e1) {
                    failed++;
                }
            }

            alert("处理完成：\n插入成功：" + done + "\n已跳过：" + skipped + "\n失败：" + failed);

        } finally {
            app.findGrepPreferences = NothingEnum.NOTHING;
            app.changeGrepPreferences = NothingEnum.NOTHING;
        }

    }, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "段首插入矩形（内联锚定）");

})();
